<template>
  <view class="takeBox">
    <u-swiper
      :list="list"
      height="400"
      indicator-pos="bottomRight"
      :circular="false"
      :title="true"
      @click="clickImage"
    ></u-swiper>
    <view class="order-content" style="background-color: #ffffff">
      <view class="order-title" style="margin-bottom: 10px">收货地址</view>
      <u-section
        :title="chooseAddress"
        sub-title="更改地址"
        color="#adb838"
        @click="toChooseAddress"
      ></u-section>
    </view>

    <!-- 操作按钮 -->
    <view class="button-sty">
      <!-- <view>下单请仔细核对订单信息</view> -->

      <view>合计</view>
      <view>￥</view>
      <view>{{ totalMoney }}</view>
      <!-- <u-button type="success" @click="submit" :style="{width:'95vw'}">提交订单</u-button> -->
      <u-button
        @click="submit"
        :style="{ width: '30vw' }"
        shape="circle"
        :custom-style="customStyle"
        :ripple="true"
        ripple-bg-color="#adb838"
        >提交订单</u-button
      >
    </view>

    <!-- 固定添加订单图标 -->
    <!-- <view
      class="custom-icon custom-icon-jia3 add-icon"
      @click="$u.debounce(addNewOrder, 500)"
    ></view> -->

    <movable-area style="width: 100%; height: 80vh">
      <view class="collapse-sty">
        <u-collapse :head-style="{ padding: '20px 10px' }">
          <u-collapse-item v-for="(item, index) in orderList" :key="index">
            <!-- slot 左边title部分 -->
            <template v-slot:title>
              <u-section
                :title="'包裹' + (index + 1) + '信息'"
                :right="false"
                color="#adb838"
              ></u-section>
            </template>
            <view class="order-content" style="min-height: 400px">
              <u-form :model="orderList[index]" :ref="'TakeBoxForm' + index">
                <u-form-item
                  label="快递编号:"
                  :label-width="this.labelWidth"
                  label-position="left"
                  prop="no"
                >
                  <u-input
                    v-model="orderList[index].no"
                    placeholder="取货码"
                    :height="80"
                  />
                </u-form-item>
                <u-form-item
                  label="快递站点:"
                  :label-width="this.labelWidth"
                  label-position="left"
                  prop="site"
                >
                  <u-input
                    v-model="orderList[index].site"
                    type="select"
                    placeholder="请选择包裹所在站点"
                    :height="80"
                    @click="addSite(index)"
                  />
                </u-form-item>
                <u-form-item
                  label="重量/价格:"
                  :label-width="this.labelWidth"
                  label-position="left"
                  prop="price"
                >
                  <u-input
                    v-model="orderList[index].price"
                    type="select"
                    placeholder="请选择包裹重量"
                    :height="80"
                    @click="addWeight(index)"
                  />
                </u-form-item>
                <u-form-item
                  label="短信复制:"
                  :label-width="this.labelWidth"
                  label-position="left"
                  prop="remark"
                >
                  <u-input
                    v-model="orderList[index].remark"
                    type="text"
                    :border="border"
                    :height="150"
                    placeholder="请复制完整的短信，方便客服取货核对"
                  />
                </u-form-item>
              </u-form>

              <u-button
                type="error"
                @click="deleteOrder(index)"
                v-show="createOrderMore"
                >删除订单</u-button
              >
            </view>
          </u-collapse-item>
        </u-collapse>
      </view>

      <!-- 移动添加按钮 -->
      <movable-view
        class="custom-icon custom-icon-jia3 add-icon"
        @click="$u.debounce(addNewOrder, 500)"
        :x="x"
        :y="y"
        direction="all"
        @change="onChange"
        v-show="createOrderMore"
      >
      </movable-view>
    </movable-area>
    <!-- 重量价格添加 -->
    <u-select
      v-model="weight_show"
      :list="weightSheetList"
      @confirm="confirm"
      title="选择对应包裹价格"
      value-name="boxPriceId"
      label-name="boxPriceName"
    ></u-select>
    <!-- 快递站点 -->
    <u-select
      v-model="site_show"
      :list="boxSite"
      title="校园快递站点"
      @confirm="siteConfirm"
      value-name="kuaidiId"
      label-name="luaidiName"
    ></u-select>

    <u-popup v-model="loading" mode="center" width="100" height="100">
      <!-- <image src="https://s1.ax1x.com/2020/09/21/wHoQk6.gif" style="width:100rpx;height:100rpx;" mode="aspectFill"></image> -->
    </u-popup>
  </view>
</template>

<script>
import { TakeBoxFormRules } from "@/common/js/formRules";
import { formatData, messageDingyue } from "@/common/js/utils";

export default {
  data() {
    return {
      schoolId: 0, //学校Id
      loading: false,
      chooseAddress: "", //选择的收货地址
      labelWidth: 120,
      weight_show: false, // 添加重量展示
      site_show: false, // 添加重量展示
      totalPrice: [], //将每个订单的价格 放到一个数组 里面 每次修改修改对应下标即可
      totalMoney: 0, //总金额
      reciveAddress: {
        name: "11111111111",
      },
      createOrderMore: true, //是否支持批量下单
      weightSheetList: [
        {
          value: "4",
          label: "江",
        },
        {
          value: "7",
          label: "湖",
        },
      ],
      customStyle: {
        backgroundColor: "#adb838", // 注意驼峰命名，并且值必须用引号包括，因为这是对象
        color: "#FFFFFF",
      },
      boxSite: [
        {
          value: "1",
          label: "中通快递",
        },
        {
          value: "2",
          label: "顺丰快递",
        },
      ],
      list: [],
      form: {
        no: "",
        site: "",
        site_id: null,
        price: "",
        truePrice: 0,
        price_id: null,
        remark: "",
      },
      // 订单数据
      orderList: [
        {
          no: "",
          site: "",
          site_id: null,
          price: "",
          truePrice: 0,
          price_id: null,
          remark: "",
        },
      ],
      nowChooseIndex: 0, //现在选择的下标
      x: 300,
      y: 570,
      old: {
        x: 0,
        y: 0,
      },
    };
  },
  onReady() {
    // 给表单 添加规则
    this.$refs.TakeBoxForm0[0].setRules(TakeBoxFormRules);
  },
  onLoad(option) {
    // console.log(option);

    // setTimeout(() => {
    //   this.loading = false
    // }, 1000);
    console.log(this.vuex_Banner);
    console.log(this.vuex_kuaidiList);
    console.log(this.vuex_priceList);

    this.boxSite = this.vuex_kuaidiList;
    this.weightSheetList = this.vuex_priceList;

    this.bannerDataForMat();

    this.schoolId = option.value;
    // 根据 选择大学站点 来动态修改大学信息
    uni.setNavigationBarTitle({
      title: option.label + "代取站点",
    });
  },
  onShow() {
    // 这里通过 vuex里面的内容 进行 拼接 收货地址
    // console.log(this.vuex_chooseAddress);
    //没有收货地址
    if (this.vuex_chooseAddress != null) {
      this.chooseAddress =
        this.vuex_chooseAddress.addressUserName +
        "-" +
        this.vuex_chooseAddress.elifeSchool.schoolName +
        "-" +
        this.vuex_chooseAddress.elifeBuild.buildName +
        "-" +
        this.vuex_chooseAddress.addressRoomId;
    } else {
      this.chooseAddress = "您还未添加收获地址(点击去添加)";
    }
    console.log(this.chooseAddress);
  },
  methods: {
    onChange: function (e) {
      this.old.x = e.detail.x;
      this.old.y = e.detail.y;
    },
    /**
     * 预览图片
     */
    clickImage(e) {
      var imgs = [];
      this.list.map((v) => {
        imgs.push(v.image);
      });
      uni.previewImage({
        current: e,
        urls: imgs,
      });
    },
    //处理传过来的Banner数据
    bannerDataForMat() {
      //获取到banner
      // console.log(this.vuex_Banner)
      this.vuex_Banner.map((v) => {
        this.list.push({
          image: v.bannerImg,
          title: v.bannerText,
        });
      });
    },
    // 修改收货地址
    toChooseAddress() {
      this.$u.route({
        url: "pages/chooseAddress/chooseAddress",
        params: {
          type: "takeBox",
        },
      });
    },
    // 重量价格点击事件   e传的是boxPriceId  boxPriceName
    confirm(e) {
      this.vuex_priceList.forEach((v) => {
        // 将获取到的id 再list里面寻找
        if (v.boxPriceId === e[0].value) {
          this.orderList[this.nowChooseIndex].price =
            e[0].label + "/" + v.boxPrice + "元";
          // 真实价格
          this.orderList[this.nowChooseIndex].truePrice = v.boxPrice;
          // 计算总价
          this.totalPrice[this.nowChooseIndex] = v.boxPrice;
          this.totalMoney = 0;
          this.totalPrice.map((v) => {
            this.totalMoney += Number(v);
          });
        }
        this.orderList[this.nowChooseIndex].price_id = e[0].value;
      });
    },
    siteConfirm(e) {
      this.orderList[this.nowChooseIndex].site = e[0].label;
      this.orderList[this.nowChooseIndex].site_id = e[0].value;
    },
    // 选择重量
    addWeight(index) {
      this.nowChooseIndex = index; //操作订单下标
      this.weight_show = true;
    },
    // 选择站点
    addSite(index) {
      this.nowChooseIndex = index; //操作订单下标
      this.site_show = true;
    },
    addNewForm() {
      var newForm = {
        no: this.form.no,
        site: this.form.site,
        price: this.form.price,
        remark: this.form.remark,
        price_id: this.form.price_id,
        site_id: this.form.site_id,
      };
      this.orderList.push(newForm);
      // 添加 新的表单需要等待1秒 等待页面重新挂载 才能将rules挂载上去
      setTimeout(() => {
        // 拼接对象名
        console.log(this.$refs["TakeBoxForm" + (this.orderList.length - 1)][0]);
        // 设置规则
        this.$refs["TakeBoxForm" + (this.orderList.length - 1)][0].setRules(
          TakeBoxFormRules
        );
      }, 1000);
    },
    // 添加新订单
    addNewOrder() {
      // 添加新订单前需要判断前一个订单 是否已经填写完毕
      // 同时需要判断是否 没有订单 添加的情况（第一个订单被客户删除的情况）
      if (this.orderList.length === 0) {
        // 直接添加新的
        this.addNewForm();
      } else {
        // 首先需要获取最后一个下标
        var lastIndex = this.orderList.length - 1;
        var lastorderIsFinish = this.jugeFromFinish(lastIndex);
        console.log(lastorderIsFinish);
        if (lastorderIsFinish) {
          this.addNewForm();
          uni.showToast({
            title: "添加成功",
            icon: "success",
            duration: 2000,
          });
        } else {
          // 提示
          uni.showModal({
            title: "提示",
            showCancel: false,
            content: `请先完成包裹${lastIndex + 1}信息填写`,
          });
        }
      }
    },
    // 删除订单
    deleteOrder(orderIndex) {
      uni.showModal({
        title: "提示",
        content: "您确定要删除该订单吗?",
        cancelText: "取消",
        confirmText: "确定",
        showCancel: true,
        success: (res) => {
          if (res.confirm) {
            // 这里删除 后相对应的虚拟节点也会被删除
            this.orderList.splice(orderIndex, 1);
          }
        },
      });
    },

    // 提交
    submit() {
      if(this.vuex_chooseAddress === null){
        this.$u.toast("请先添加收货地址")
        return
      }
      // 需要检测 所有的表单数据 是否都满足 检测规则
      let promiseList = [];
      for (let index = 0; index < this.orderList.length; index++) {
        var p = new Promise((resolve, reject) => {
          this.$refs["TakeBoxForm" + index][0].validate((valid) => {
            if (valid) {
              resolve();
            } else {
              reject();
            }
          });
        });
        promiseList.push(p);
      }
      Promise.all(promiseList)
        .then(() => {
          console.log("全部通过");
          console.log(this.orderList);
          console.log(this.vuex_chooseAddress);
          messageDingyue().then(() => {
            //订单信息 存入 Vuex
            this.$u.vuex("vuex_orderInfo", {
              schoolId: this.schoolId,
              orderList: this.orderList,
              address: this.vuex_chooseAddress,
            });
            this.$u.route({
              url: "pages/order/components/orderInfo",
              params: {
                schoolId: this.schoolId,
              },
            });
          });
        })
        .catch((e) => {
          console.log("不通过");
        });
    },
    // 判断该表单是否已经完成 填写
    jugeFromFinish(index) {
      var isSuccess = false;
      this.$refs["TakeBoxForm" + index][0].validate((valid) => {
        if (valid) {
          isSuccess = true;
        } else {
          isSuccess = false;
        }
      });
      return isSuccess;
    },
  },
};
</script>

<style scoped lang ='less' >
.takeBox {
  background-color: #eff5f7;
  min-height: 100vh;
  .order-content {
    margin-top: 10px;
    background-color: #eff5f7;
    padding: 10px;
    .order-title {
      text-align: center;
      font-size: 16px;
      color: #5a5b5c;
    }
    .order-right {
      display: flex;
      flex-direction: row;
      color: #adb838;
      & > view:nth-child(1) {
        margin-right: 5px;
      }
    }
  }
  .collapse-sty {
    margin-top: 10px;
    background-color: #ffffff;
  }
  .button-sty {
    background-color: #ffffff;
    display: flex;
    flex-direction: row;
    justify-content: flex-end;
    align-items: center;
    padding: 10px;
    width: 100vw;
    z-index: 888;
    margin-top: 10px;
    position: fixed;
    bottom: 0;
    left: 0;
    & > view:nth-child(1) {
      color: #666;
    }
    & > view:nth-child(2) {
      color: #ee0a40;
    }
    & > view:nth-child(3) {
      color: #ee0a40;
      font-size: 20px;
      margin-right: 10px;
    }
  }
  .add-icon {
    position: fixed;
    bottom: 80px;
    right: 25px;
    font-size: 45px;
    color: #adb838;
    z-index: 9999;
  }
}
::-webkit-scrollbar {
  width: 0;
  height: 0;
  color: transparent;
}
</style>
